<template>
  <el-form ref="ruleFormRef" style="max-width: 100%" :model="ruleForm" :rules="rules" label-width="auto"
    class="demo-ruleForm" status-icon>
    <el-form-item label="商品编码" prop="code">
      <el-input v-model="ruleForm.code" placeholder="请输入商品编码" />
    </el-form-item>
    <el-form-item label="商品名称" prop="name">
      <el-input v-model="ruleForm.name" placeholder="请输入商品名称" />
    </el-form-item>
    <el-form-item label="所属分类" prop="kid">
        <el-tree-select
            v-model="ruleForm.kid"
            :data="kindOptions"
            check-strictly
            :render-after-expand="false"
        />
    </el-form-item>
    <el-form-item label="商品单位" prop="uid">
      <el-select-v2 v-model="ruleForm.uid" placeholder="请选择" :options="unitOptions" />
    </el-form-item>
    <el-form-item label="税率" prop="tax">
      <el-input v-model.number="ruleForm.tax" type="number" placeholder="请输入税率" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm()">提交</el-button>
      <el-button @click="resetForm()">重置</el-button>
      <el-button @click="emitCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { Good } from "@/types/basic/good.ts";
import { ElMessage } from 'element-plus'

const emit = defineEmits(['submit-success', 'cancel']);

// 下拉选项
interface Option { value: number, label: string }
const unitOptions = ref<Option[]>([])

interface TreeNode {
  value: number
  label: string
  children?: TreeNode[]
}

// 响应式变量声明
const kindOptions = ref<TreeNode[]>([])

// 获取分类数据方法
async function loadKindOptions() {
  try {
    const response = await request.post('basic/goodsCategory/showGoodsCategoryByTree')
    const rawData = response.data.data
    kindOptions.value = convertTreeData(rawData)
    console.log('处理后的分类数据:', kindOptions.value)
  } catch (e: any) {
    ElMessage.error('加载分类失败: ' + e.message)
  }
}

// 树形数据转换函数
function convertTreeData(nodes: any[]): TreeNode[] {
  return nodes.map(node => ({
    value: node.id, // 确保与后端数据类型一致（数值或字符串）
    label: node.name,
    children: node.children ? convertTreeData(node.children) : []
  }))
}

console.log(kindOptions)

async function loadUnitOptions() {
  try {
    const res = await request.post('basic/unit/getAllUnit', {});
    const list = res.data.data as Array<{ id: number, name: string }>;
    unitOptions.value = list.map(item => ({ value: item.id, label: item.name }));
  } catch (e: any) {
    ElMessage.error('加载商品单位失败: ' + e.message);
  }
}

onMounted(async () => {
  await loadKindOptions();
  await loadUnitOptions();
});

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<Good>({
  id: undefined,
  code: '',
  name: '',
  tax: 0,
  kid: undefined,
  uid: undefined,
  createUser: user.user.name,
  updateUser: user.user.name,
})

const rules = reactive<FormRules<Good>>({
  code: [
    { required: true, message: '请输入商品编码', trigger: ['blur', 'change'] },
    { min: 3, max: 10, message: '商品编码长度应为3到10个字符', trigger: ['blur', 'change'] }
  ],
  name: [
    { required: true, message: '请输入商品名称', trigger: ['blur', 'change'] },
    { min: 2, max: 50, message: '商品名称长度应为2到50个字符', trigger: ['blur', 'change'] }
  ],
  kid: [
    { required: true, message: '请选择商品种类', trigger: 'change' }
  ],
  uid: [
    { required: true, message: '请选择商品单位', trigger: 'change' }
  ],
  tax: [
    { required: true, message: '请输入税率', trigger: ['blur', 'change'] },
    { type: 'number', min: 0, max: 100, message: '税率必须大于0小于100', trigger: ['blur', 'change'] }
  ]
})

const props = defineProps<{ good?: Good | null }>();

watch(() => props.good, (newGood) => {
  if (newGood && newGood.id) {
    Object.assign(ruleForm, newGood);
  } else {
    ruleForm.id = undefined;
    ruleForm.code = '';
    ruleForm.name = '';
    ruleForm.tax = 0;
    ruleForm.kid = undefined;
    ruleForm.uid = undefined;
  }
}, { immediate: true });

const submitForm = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = ruleForm.id ? 'basic/good/updateGood' : 'basic/good/addGood'
        await request.post(url, ruleForm);
        ElMessage.success(ruleForm.id ? '更新商品成功' : '新增商品成功');
        emit('submit-success');
      } catch (error: any) {
        ElMessage.error('操作失败，请稍后重试');
        console.error(error);
      }
    } else {
      ElMessage.warning('请完善表单信息');
    }
  });
};

const resetForm = () => {
  ruleFormRef.value?.resetFields();
};

const emitCancel = () => {
  emit('cancel');
};
</script>

<style scoped>
.demo-ruleForm {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.el-input input[type="number"]::-webkit-inner-spin-button,
.el-input input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
.el-input input[type="number"] {
  -moz-appearance: textfield;
}
</style>